package com.appium.base;

import java.io.File;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.appium.java_client.service.local.AppiumServerHasNotBeenStartedLocallyException;

public class BaseDriver {
	public AppiumDriver<WebElement> driver;
	private static AppiumDriverLocalService service;

	@BeforeClass
	public void setUp() throws Exception {
		service = AppiumDriverLocalService.buildDefaultService();
		service.start();

		if (service == null || !service.isRunning()) {
			throw new AppiumServerHasNotBeenStartedLocallyException("An appium server node is not started!");
		}
		File classpathRoot = new File(System.getProperty("user.dir"));
		File appDir = new File(classpathRoot, "/apps/");
		File app = new File(appDir, "gljr.apk");
		DesiredCapabilities capabilities = new DesiredCapabilities();
		capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
		capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
		// capabilities.setCapability(MobileCapabilityType.NO_RESET, "false");
		capabilities.setCapability("appPackage", "com.goli.androidapp");
		capabilities.setCapability("appActivity", ".activity.SplashScreen");
		driver = new AndroidDriver<>(service.getUrl(), capabilities);
	}

	@AfterClass
	public void tearDown() throws Exception {
		if (driver != null) {
			driver.quit();
		}
		if (service != null) {
			service.stop();
		}
	}

	public MobileElement scrollTo(String text) {
		return (MobileElement) driver.findElement(MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector()"
				+ ".scrollable(true)).scrollIntoView(resourceId(\"android:id/list\")).scrollIntoView("
				+ "new UiSelector().text(\"" + text + "\"))"));
	}

	public AppiumDriver<?> getDriver() {
		return driver;
	}

}
